import {Component, OnInit} from '@angular/core';
import {FormField} from '../model/FormField';
import {NzDrawerService, NzModalService} from 'ng-zorro-antd';
import {EditFormItemComponent} from './edit-form-item/edit-form-item.component';
import {DynamicFormDataService} from '../dynamic-form-data.service';
import {FlexibleFormEditComponent} from '../../../shared/component/flexible-form-edit/flexible-form-edit.component';

const uuid = require('uuid');

@Component({
  selector: 'app-create-form',
  templateUrl: './create-form.component.html',
  styleUrls: ['./create-form.component.css']
})
export class CreateFormComponent implements OnInit {

  formId = 1;

  mapOfExpandData: { [key: string]: boolean } = {};
  id: string;
  fields: FormField[];
  formName: string;
  formDesc: string;

  constructor(private drawerService: NzDrawerService,
              private formDataService: DynamicFormDataService,
              private modalService: NzModalService) {
  }

  ngOnInit(): void {
    const formData = this.formDataService.getFormData();
    if (formData) {
      this.id = formData.id;
      this.formName = formData.name;
      this.formDesc = formData.desc;
      this.fields = formData.formItem;
      this.fields.forEach(field => {
        if (field.formId >= this.formId) {
          this.formId = field.formId + 1;
        }
      });
      this.formDataService.clearFormData();
    } else {
      this.fields = [];
    }
  }

  addFormElement() {
    this.openComponent('新增控件');
  }

  openComponent(title: string, elementData?: any): void {
    const drawerRef = this.drawerService.create<EditFormItemComponent, { value: any, formId: any }, string>({
      nzTitle: title,
      nzWidth: 750,
      nzContent: EditFormItemComponent,
      nzMaskClosable: false,
      nzKeyboard: false,
      nzContentParams: {
        value: elementData,
        formId: elementData ? elementData.formId : this.getFormId()
      }
    });

    drawerRef.afterClose.subscribe((value: any) => {
      if (value) {
        const oldItem = this.fields.find(item => item.formId === value.formId);
        if (oldItem) {
          const index = this.fields.findIndex(item => item.formId === value.formId);
          this.fields[index] = value;
          this.fields = [...this.fields];
        } else {
          const addElement = new FormField(value.formId, value.id, value.name, value.type, value.required,
            value.formId, value.isMultiple, value.optionSource, value.options, value.placeholder,
            value.validators, value.labelWidth, value.controlWidth, value.emptyHidden);
          this.fields = [...this.fields, addElement];
        }
      }
    });
  }

  openEditDrawer(data) {
    this.openComponent('修改控件', data);
  }

  private getFormId() {
    return this.formId++;
  }

  elementUp(index: number) {
    const current = JSON.parse(JSON.stringify(this.fields[index]));
    const previous = JSON.parse(JSON.stringify(this.fields[index - 1]));
    this.changeSort(current, previous);
    this.fields[index - 1] = current;
    this.fields[index] = previous;
    this.fields = [...this.fields];
  }

  elementDown(index: number) {
    const current = JSON.parse(JSON.stringify(this.fields[index]));
    const next = JSON.parse(JSON.stringify(this.fields[index + 1]));
    this.changeSort(current, next);
    this.fields[index + 1] = current;
    this.fields[index] = next;
    this.fields = [...this.fields];
  }

  private changeSort(previous, next) {
    const temp = previous.sort;
    previous.sort = next.sort;
    next.sort = temp;
  }

  saveForm() {
    // currently use mem cache save form
    const list = localStorage.getItem('dynamicFormList');
    let temp;
    if (list) {
      temp = JSON.parse(list);
      temp.push(JSON.stringify({id: this.id ? this.id : uuid.v4(), name: this.formName, desc: this.formDesc, formItem: this.fields}));
    } else {
      temp = [JSON.stringify({id: this.id ? this.id : uuid.v4(), name: this.formName, desc: this.formDesc, formItem: this.fields})];
    }
    localStorage.setItem('dynamicFormList', JSON.stringify(temp));
  }

  openPreviewModal() {
    this.modalService.create({
      nzTitle: '预览模板',
      nzContent: FlexibleFormEditComponent,
      nzComponentParams: {
        formJson: JSON.stringify(this.fields)
      },
      nzWidth: 800,
      nzBodyStyle: {height: '500px'},
      nzStyle: {top: '5vh'}
    });
  }
}
